package com.zlm.test;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * Author: Harbour
 * Date: 2021-05-08 9:59
 * Desc: 第一个WordCount Flink程序
 */
public class WordCount {
    public static void main(String[] args) throws Exception {
        // step 1. 创建运行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSet<String> dataSource = env.readTextFile("D:\\JavaProject\\real-time-data-warehouse\\learning\\src\\main\\resources\\wc.txt");

        dataSource.flatMap(new MyFlatMapper())
                .groupBy(0)
                .sum(1)
                .print();
    }

    // step 3. 自定义flat mapper
    static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] strs = s.split(" ");

            for (String str : strs) {
                collector.collect(new Tuple2<>(str, 1));
            }

        }
    }
}
